<template>
  <div class="dt-content-project-card">
    <el-badge :value="item.unread || ''" v-for="item in projectListWithTooltip" :key="item.id" class="dt-content-project-badge" :max="99">
      <div @click="goDetail(item)">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip :open-delay="500" class="item" effect="dark" :content="item.projectName" placement="top-start" :disabled="!item.tooltip">
              <span class="project-name" ref="projectName">{{ item.projectName }}</span></el-tooltip>
            <el-dropdown trigger="click" placement="bottom-start" @command="handleCommand">
              <em @click.stop><i class="project-more el-icon-more"></i></em>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="item.projectState !== 2 && item.projectState !== 0" :command="{ type: 1, item: item }">标记完成</el-dropdown-item>
                <el-dropdown-item v-if="item.projectState !== 1 && item.projectState !== 0" :command="{ type: 3, item: item }">重新启动</el-dropdown-item>
                <el-dropdown-item v-if="item.projectState !== 3" :command="{ type: 2, item: item }">删除项目</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div :class="getClassName(item)">
            <p>
              <i class="el-icon-remove-outline" v-if="item.projectState == '0'"></i>
              <i class="el-icon-time" v-else></i>
              <span>{{ item.projectState | projectStateName }}</span>
            </p>
          </div>
          <div class="dt-content-project-card-text">
            <p>
              <span>产值：</span>
              <span v-if="isMaster(item)">{{ item.output | formatNumberToWan }}</span>
              <span v-else>***</span>
            </p>
          </div>
          <div class="dt-content-project-card-text">
            <p>
              <span>创建人：</span>
              <span>{{ item.createUname }}</span>
            </p>
          </div>
          <div class="dt-content-project-card-text">
            <p>
              <span>负责人：</span>
              <span>{{ item.masterName }}</span>
            </p>
          </div>
          <div class="dt-content-project-card-text">
            <p>
              <span>任务总数：</span>
              <span>{{ item.taskCount }}</span>
            </p>
          </div>
          <div class="dt-content-project-card-text mb12">
            <p class="dt-content-project-card-text-flex">
              <span>工期：</span>
              <span>{{ item.startTime | formatDateYMD }}至{{ item.endTime | formatDateYMD }}</span>
              <span v-if="item.remainDays > 0">余{{ item.remainDays }}天</span>
              <span v-else style="color: #f5222d">延期{{ -item.remainDays }}天</span>
            </p>
          </div>
          <div>
            <el-progress :text-inside="true" :stroke-width="16" :percentage="item.projectProgress" color="#85A5FF" text-color="#1f1f1f"
              define-back-color="#f0f5ff"></el-progress>
          </div>
        </el-card>
      </div>
    </el-badge>
  </div>
</template>
<script>
export default {
  props: {
    ProjectList: Array, // 指定prop为Array类型
    ActiveName: {
      type: [String], // 可以是字符串
      required: true, // 必填项
      default: '0' // 如果没有传递，则使用默认值
    }
  },
  data() {
    return {
      // 创建一个本地数据属性来存储带有 tooltip 的项目列表
      localProjectList: [],
      uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id
      currStep: -1
    }
  },
  watch: {
    ProjectList(newVal, oldVal) {
      this.localProjectList = newVal.map((item, index) => {
        const tooltip = this.getProjectNameTooltip(item.projectName, index)
        return {
          ...item,
          tooltip
        }
      })
    }
  },
  filters: {
    // formatNumberToWan: function (num) {
    //   if (num >= 10000) {
    //     let wan = (num / 10000).toFixed(4)
    //     // 移除末尾的0，但至少保留两位小数
    //     wan = wan.replace(/(\.\d*?[1-9])0+$|\.0*$/, '$1')
    //     return wan + '万'
    //   } else {
    //     return num.toString()
    //   }
    // },
    formatNumberToWan: function (num) {
      // 将数字转换为字符串，并去除末尾多余的零
      let numStr = num.toFixed(2).replace(/(\.\d*?[1-9])0+$|\.0*$/, '$1')

      // 分割整数和小数部分
      let [integerPart, decimalPart] = numStr.split('.')

      // 转换整数部分为字符串数组，并添加逗号分隔
      integerPart = integerPart.split('').reverse().join('')
      integerPart = integerPart.replace(/(\d{3})(?=\d)/g, '$1,')
      integerPart = integerPart.split('').reverse().join('')

      // 格式化万和元
      if (num >= 10000) {
        let wanPart = Math.floor(num / 10000) // 获取万的部分
        let yuanPart = Math.floor(num % 10000) // 获取元的部分
        let wanStr = wanPart.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,') + '万'
        let yuanStr = yuanPart.toString().padStart(4, '0').replace(/^0+/, '')

        if (yuanStr !== '') {
          if (decimalPart) {
            yuanStr += '.' + decimalPart
          }
          yuanStr += '元'
        }

        return wanStr + yuanStr
      } else {
        // 如果金额小于1万，直接返回元部分，并确保处理小数点
        return integerPart + (decimalPart ? '.' + decimalPart : '') + '元'
      }
    },

    formatDateYMD: function (value) {
      if (!value) return ''
      const date = new Date(value)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    projectStateName(value) {
      if (value == 0) {
        return '待发布'
      }
      if (value == 1) {
        return '进行中'
      }
      if (value == 2) {
        return '已完成'
      }
      if (value == 3) {
        return '回收站'
      }
    }
  },
  computed: {
    // 使用计算属性来返回带有 tooltip 的项目列表
    projectListWithTooltip() {
      return this.localProjectList.map((item, index) => ({
        ...item
      }))
    }
  },
  methods: {
    isMaster(item) {
      //创建人或者管理
      var uid = parseInt(this.uid),
        isCreater = item.createUid === uid,
        masters = item.masterUid.split(','),
        isMaster = masters.includes(this.uid)

      return isCreater || isMaster
    },
    getClassName(item) {
      let className = ''
      switch (item.projectState) {
        case 0:
          className = 'dt-content-project-card-state-wait'
          break
        case 1:
          className = 'dt-content-project-card-state-ongoing'
          break
        case 2:
          className = 'dt-content-project-card-state-completed'
          break
        case 3:
          className = 'dt-content-project-card-state-paused'
          break
        default:
          className = ''
          break
      }
      return className
    },
    getProjectNameTooltip(projectName, index) {
      const projectNameElement = this.$refs.projectName[index] // 获取第一个projectName元素的引用
      if (projectNameElement) {
        const projectNameWidth = projectNameElement.scrollWidth
        const containerWidth = projectNameElement.clientWidth // 容器的实际宽度
        if (projectNameWidth > containerWidth) {
          return true
        }
      }
      return false
    },
    /**
     *
     * @param item 项目卡片信息对象
     * 项目标记完成
     */
    MarkFinished(item) {
      var data = [{ userId: this.uid, rootProjectId: item.id }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/markProject'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              if (this.ActiveName == '0') {
                this.localProjectList.map((items) => {
                  if (items.id === item.id) {
                    items.projectState = 2
                  }
                })
              }
              if (this.ActiveName !== '0') {
                this.localProjectList.map((items) => {
                  if (items.id === item.id) {
                    items.projectState = 2
                  }
                })
                this.localProjectList = this.localProjectList.filter((items) => items.id !== item.id)
              }
              this.$message.success(data.message)
            } else {
              this.$message.error(data.message)
            }
          })
        })
        .catch((error) => {})
    },
    DelProject(item) {
      var data = [{ userId: this.uid, rootProjectId: item.id }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/deleteProject'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              if (this.ActiveName == '0') {
                this.localProjectList.map((items) => {
                  if (items.id === item.id) {
                    items.projectState = 3
                  }
                })
                this.localProjectList = this.localProjectList.filter((items) => items.id !== item.id)
              }
              if (this.ActiveName !== '0') {
                this.localProjectList.map((items) => {
                  if (items.id === item.id) {
                    items.projectState = 3
                  }
                })
                this.localProjectList = this.localProjectList.filter((items) => items.id !== item.id)
              }
              this.$message.success(data.message)
            } else {
              this.$message.error(data.message)
            }
          })
        })
        .catch((error) => {})
    },
    rebootProject(item) {
      var data = [{ userId: this.uid, rootProjectId: item.id }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/restartProject'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              if (this.ActiveName == '0') {
                this.localProjectList.map((items) => {
                  if (items.id === item.id) {
                    items.projectState = 1
                  }
                })
                // this.localProjectList = this.localProjectList.filter((items) => items.id !== item.id)
              }
              if (this.ActiveName !== '0') {
                this.localProjectList.map((items) => {
                  if (items.id === item.id) {
                    items.projectState = 1
                  }
                })
                this.localProjectList = this.localProjectList.filter((items) => items.id !== item.id)
              }
              this.$message.success(data.message)
            } else {
              this.$message.error(data.message)
            }
          })
        })
        .catch((error) => {})
    },
    handleCommand(command) {
      if (command.type === 1) {
        this.MarkFinished(command.item)
      }
      if (command.type === 2) {
        this.DelProject(command.item)
      }
      if (command.type === 3) {
        this.rebootProject(command.item)
      }
    },
    goDetail(item) {
      if (item.projectState == 0) {
        this.$router.push('/main/#/pm?tab=create&elTab=0&rootProjectId=' + item.id)
      } else {
        this.$socket.emit('joinProject', 'project-' + item.id)
        this.$router.push('/main/#/pm?tab=detail&elTab=0&rootProjectId=' + item.id, () => {
          //新手引导,跳转后等待dom加载完毕再进行回调
          if (this.currStep === 1) {
            var timer = setInterval(() => {
              if ($('.dt-content-page')[0]) {
                clearInterval(timer)
                this.$root.$emit('guide-to-2')
              }
            }, 50)
          }
        })
      }
    }
  },
  mounted() {
    // 使用 mounted 钩子函数来初始化 localProjectList
    this.localProjectList = [...this.ProjectList]
    this.$nextTick(() => {
      this.localProjectList = this.localProjectList.map((item, index) => {
        const tooltip = this.getProjectNameTooltip(item.projectName, index)
        return {
          ...item,
          tooltip
        }
      })
    })

    //全局监听新手引导
    this.$root.$on('guide-to-1', () => {
      this.currStep = 1
    })
    this.$root.$on('guide-to-close', () => {
      this.currStep = -1
    })
    this.$root.$on('guide-to-end', () => {
      this.currStep = -1
    })
    var timer = setInterval(() => {
      if (this.$socket) {
        clearInterval(timer)
        this.$socket.on('project_group_unread', (data) => {
          var _data = JSON.parse(data)
          if (
            this.localProjectList.find((item) => {
              return item.id == _data.rootProjectId
            })
          ) {
            this.localProjectList.find((item) => {
              return item.id == _data.rootProjectId
            }).unread = _data.projectUnread
          }
        })
      }
    }, 10)
  }
}
</script>
<style scoped>
.dt-content-project-card {
  display: flex;
  flex-wrap: wrap;
}
.dt-content-project-badge {
  /* width: 14.5%; */
  width: 280px;
  margin-left: 16px;
  margin-top: 16px;
}
.box-card {
  /* width: 100%; */
  cursor: pointer;
  padding: 16px 14px 20px 14px;
  border-radius: 0px;
  border: none;
}
.box-card >>> .el-card__header {
  border: none;
  padding: 0;
}
.el-card__header > div {
  display: flex;
}
.el-card__header > div > .project-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 16px;
  color: #1f1f1f;
  flex: 1;
  padding: 1px;
  font-weight: bold;
  line-height: 1.3;
  padding-right: 10px;
}
.box-card >>> .el-card__body {
  padding: 0;
}
.dt-content-project-card-state-ongoing,
.dt-content-project-card-state-completed,
.dt-content-project-card-state-paused,
.dt-content-project-card-state-wait {
  margin-top: 8px;
  margin-bottom: 10px;
}
.dt-content-project-card-state-ongoing > p,
.dt-content-project-card-state-completed > p,
.dt-content-project-card-state-paused > p,
.dt-content-project-card-state-wait > p {
  width: 74px;
  height: 24px;
  box-sizing: border-box;
  line-height: 22px;
  border: 1px solid #fff1b8;
  background-color: #fffbe6;
  font-size: 12px;
  color: #faad14;
  padding-left: 8px;
}
.dt-content-project-card-state-completed > p {
  border: 1px solid #d9f7be;
  background-color: #f6ffed;
  color: #52c41a;
}
.dt-content-project-card-state-wait > p {
  border: 1px solid #ced2db;
  background-color: #fafafa;
  color: #606266;
}
.dt-content-project-card-state-ongoing > p > span,
.dt-content-project-card-state-completed > p > span,
.dt-content-project-card-state-paused > p > span,
.dt-content-project-card-state-wait > p > span {
  margin-left: 6px;
}
.dt-content-project-card-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 6px !important;
}
/* .dt-content-project-card-text > p {
  margin-bottom: 6px !important;
} */
.dt-content-project-card-text-flex {
  display: flex;
  justify-content: space-between;
}
.dt-content-project-card-text-flex > span:nth-of-type(2) {
  flex: 1;
  padding-left: 5px;
}
.mb12 {
  margin-bottom: 12px !important;
}
.el-popper.dt-content-project-popper {
  width: 140px !important;
}
.project-more {
  color: #ced2db;
}

.dt-content-project-card >>> .el-badge__content.is-fixed {
  top: -10px;
  transform: none;
  right: -6px;
}
</style>
